import { debounce, throttle } from "lodash-es";
import * as monaco from 'monaco-editor';

import { createEditor } from "./editor";

import "./index.less";

// const day = Date().getDay();
var date = new Date();
const uuid = `${date.getYear()}-${date.getMonth()}-${date.getDate()}`;

let hashId = location.hash?.substring(1) || "interval";
let editor, chart, options;

main();

async function main() {
  editor = createEditor(document.querySelector("#editor"));
  const updateChart = debounce(() => {
    try {
      const options = JSON.parse(editor.getValue());
      chart?.refreshData(options);
    } catch (e) {
      console.warn(e);
    }
  }, 1000);

  // const startLoading = throttle(startLoading, 1000);

  editor.onDidChangeModelContent(updateChart);

  await initNav();
}

async function initNav() {
  const navContainer = document.querySelector("#nav");
  const res = await fetch("/demo/manifest.json?"+uuid);
  const { demos } = await res.json();
  
  navContainer.innerHTML = demos.map(({ title, children}) => {
    return `<div class="category">
      <div class="title">${title}</div>
      ${children.map(({title, id}) => {
        return '<div class="chart-item" data-id="' + id + '">' + title + '</div>';
      }).join("\n")}
    </div>`
  }).join("\n");

  if (hashId) {
    document.querySelector(`[data-id="${hashId}"]`)?.setAttribute("selected", "");
    updateOptions();
  }

  navContainer.addEventListener("click", function (e) {
    const { target } = e;
    const id = target.dataset?.id
    if (!id) return;
    if (id === hashId) return;

    document.querySelector(`[data-id="${hashId}"]`)?.removeAttribute("selected");
    target.setAttribute("selected", "");
    history.pushState(null, "", `#${id}`);
    hashId = id;

    updateOptions();
  });
}

async function updateOptions() {
  const res = await fetch(`/demo/${hashId}.json?${uuid}`);
  const json = await res.json();
  editor.setValue(JSON.stringify(json, null, 4));
  renderChart(json);
}

function renderChart(options) {
  if (!chart) {
    chart = new Van.VanChart(document.querySelector("#chart"), options);
  }
}

// function startLoading() {
//   let loadingContainer = document.querySelector("#loading");
//   if (!loadingContainer) {
//     loadingContainer = document.createElement("div");
//     loadingContainer.id = "loading";
//     loadingContainer.innerHTML = `<div class="progress"></div>`;
//   }
//   const progress = loadingContainer.querySelector(".progress");
// }